<template>
  <div class="nsqaPost ct">
    <el-breadcrumb class="head-nav" :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/nsqa' }">农事问答</el-breadcrumb-item>
      <el-breadcrumb-item>提出问题</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="detail-content">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
      <el-form-item label="问题简介" prop="question">
        <el-input v-model="ruleForm.question"  autocomplete="off" />
      </el-form-item>

      <el-form-item label="是否置顶" prop="question">
        <el-switch v-model="ruleForm.isTop"  autocomplete="off" />
      </el-form-item>


      <el-form-item label="问题类型" prop="question">
        <el-cascader v-model="ruleForm.type1" clearable :props="props" placeholder='选择问题类型'/>
      </el-form-item>

      <el-form-item label="问题详情" prop="questionDesc">
        <el-input
          v-model="ruleForm.questionDesc"
          type="textarea"
          autocomplete="off"
          :autosize="{ minRows: 12, maxRows: 20 }"
        />
      </el-form-item>
      <el-form-item label="上传照片" prop="questionImg">
        <el-upload
        class="avatar-uploader"
        list-type="picture-card"
        :http-request="uploadFilePromise"
        action="#" 
        :limit="1"
        :on-remove="handleRemove"
        :file-list="fileList"
      > 
        <el-icon @click="uploadFilePromise(scope)"><Plus /></el-icon>
      </el-upload>
      </el-form-item>
      <el-form-item class="sbumiot">
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          提交问题
        </el-button>
        <!-- <el-button @click="resetForm(ruleFormRef)">Reset</el-button> -->
      </el-form-item>
      </el-form>
    </div>

    <!-- <el-dialog :width="500" v-model="dialogVisible">
    <img :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog> -->
  </div>
</template>
<script setup>
  import { ArrowRight } from '@element-plus/icons-vue'
  import { computed, reactive, ref } from 'vue'
  import { getTxCosCredential, saveForum, saveQuestion, listFirstType, listSecondaryType } from '@/api/home'
  import COS from 'cos-js-sdk-v5'
  import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue';
  import { ElMessageBox } from 'element-plus'
  import { useRouter } from 'vue-router';

  const router = useRouter();


  const stsToken = ref({});

  const first = ref([]);
  const first1 = ref([]);


  const getlistFirstType = async () => {
    const ret = await listFirstType();
    console.log('aaa',ret)
    first.value = (ret?.data || [])?.map((item,indx) => ({
        value: item.firstTypeId,
        label: item.firstType,
        leaf: false
    }));
  }

  const getlistSecondaryType = async (firstTypeIds) => {
    const ret = await listSecondaryType({
      firstTypeIds
    });
    console.log('bbb',ret)
    first1.value = (ret?.data || [])?.filter(item => item.firstTypeId == firstTypeIds).map((item,indx) => ({
        value: item.secondaryTypeId,
        label: item.secondaryType,
        leaf: true
    }));
  };

  getlistFirstType();

  const props = computed(() => {
    return  {
    lazy: true,
    async lazyLoad(node, resolve) {
      const { level, value } = node;
      if(level == 0) {
        if(!first.value?.length) {
          await getlistFirstType();
          resolve(first.value)
        } else { 
          resolve(first.value)
        }
      } else if (level == 1) {
        await getlistSecondaryType(value);
        resolve(first1.value)
      }
      // setTimeout(() => {
      //   const nodes = Array.from({ length: level + 1 }).map((item) => ({
      //     value: ++id,
      //     label: `Option - ${id}`,
      //     leaf: level >= 2,
      //   }))
      //   // Invoke `resolve` callback to return the child nodes data and indicate the loading is finished.
      //   resolve(nodes)
      // }, 1000)
    },
  }
  })


  const fileList = computed(() => {
    if(ruleForm.questionImg) {
      return [{
        id: '0',
        name: '1',
        url: ruleForm.questionImg
      }]
    }
    return []
  })

  const handleRemove = () => {
    fileList.value = [];
    ruleForm.questionImg = '';
  }

  const uploadFilePromise = (file) => {
    if(!file) return
    getTxCosCredential().then(res=> {
      stsToken.value = res.data;
      const cos = new COS({
      getAuthorization: function(option, callback) {
        callback({
          TmpSecretId: stsToken.value.credentials.tmpSecretId,
          TmpSecretKey: stsToken.value.credentials.tmpSecretKey,
          XCosSecurityToken: stsToken.value.credentials.sessionToken,
          ExpiredTime: stsToken.value.expiredTime
        })
      }
      })
		  uploadFile(cos,file.file)
    })
	}

  const uploadFile =  (cos, file)=> {
    cos.putObject(
      {
        Bucket: stsToken.value.bucket,  // 存储桶名称
        Region: stsToken.value.region, // 地区
        Key:`/uploads/zizhi/${new Date().getTime()}${file.name}` , // 图片名称
        Body: file,
        onHashProgress: function (progressData) {
          console.log ('校验中', JSON.stringify (progressData));
        },
        onProgress: function (progressData) {
          console.log ('上传中', JSON.stringify (progressData));
        },
      },
      function (err, data) {
        if (err) {
          // this.error(file)
          return;
        }
        console.log('----data',data)
        if(data?.statusCode==200 && data?.Location) {
          _$.$message({type: 'success',message:'上传成功'})
          ruleForm.questionImg = `${location.protocol}//${data.Location}`
        } else {
          _$.$message({type: 'success',message:'上传失败，请重新上传'})
        }

        // fileList.value = [{
        //   name: '1',
        //   url: `http://${data.Location}`
        // }]
      }
    );
	}

  // const beforeAvatarUpload = (rawFile) => {
  //   if (rawFile.type !== 'image/jpeg') {
  //     ElMessage.error('Avatar picture must be JPG format!')
  //     return false
  //   } else if (rawFile.size / 1024 / 1024 > 2) {
  //     ElMessage.error('Avatar picture size can not exceed 2MB!')
  //     return false
  //   }
  //   return true
  // }

  const ruleFormRef = ref()
  const ruleForm = reactive({
    question: '',
    questionDesc: '',
    questionImg: '',
    type1: [],
    isTop: false,
  })

  const rules = reactive({
    question: [{  required:  true }],
    questionDesc: [{required:  true }]
  })

  const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate(async(valid) => {
      if (valid) {
        console.log('submit!')
        console.log('--', ruleForm)
        const ret = await saveForum({
          // params: ruleForm
          params: {
            firstTypeId: ruleForm.type1[0],
            secondaryTypeId: ruleForm.type1[1],
            title: ruleForm.question,
            content: ruleForm.questionDesc,
            imageList: ruleForm.questionImg ? [ruleForm.questionImg] : [],
            isTop: ruleForm.isTop
          }
        });
        if(ret?.code === '200') {
          _$.$message({type: 'success',message:  '提问成功'})
          setTimeout(() => {
            router.back()
            // router.push('/nsqa')
          }, 1000)
        } else {
          _$.$message({type: 'error',message:  '网络异常'})
        }
        console.log('000ret', ret)
      } else {
        console.log('error submit!')
        _$.$message({type: 'error',message:  '网络异常'})

      }
    })
  }
</script>

<style lang="scss" scoped>
.nsqaPost {
  flex: 1;
  width: 100%;
  display: flex;
  flex-direction: column;
  color: #777;
  padding: 0 10%;
  background: #f8f8f8 url('../../assets/job/6.png') no-repeat 0 200px;
  :deep(.demo-ruleForm) {
    input, textarea {
      font-size: 20px;
    }
    .el-form-item__label {
      font-size: 18px;
    }
    .el-form-item__error {
      font-size: 20px;
    }
    .avatar-uploader {
      
    .el-upload, .el-upload-list {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      width: 178px;
      height: 178px;
      margin: 0;
      .el-upload-list__item {
        width: 178px !important;
        height: 178px !important;
        margin: 0;
      }
    .el-upload-list__item-thumbnail {
        object-fit: cover !important;
      }
    }
    .el-upload-list__item-preview {
      display: none;
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    }
  }
  .head-nav {
    height: 125px;
    display: flex;
    align-items: center;
    font-size: 24px;
  }
  .detail-content {
    display: flex;
    margin-bottom: 60px;
    min-height: 760px;
    .demo-ruleForm {
      width: 100%;
      .el-form-item {
        align-items: center;
        margin-bottom: 40px;
      }
      :deep(.el-form-item__label-wrap) {
        margin-right: 20px;
        label {
          font-size: 18px;
        }
      }
      :deep(.el-form-item__content) {
        .el-input {
          height: 50px;
        }
      }
      .sbumiot {
        :deep(.el-form-item__content) {
          display: flex;
          justify-content: center;
   
          .el-button {
            height: 70px;
            width: 260px;
            font-size: 30px;
            font-weight: normal;
          }
        }
      }
      .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
      }
    }
  }
}
</style>